<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./lib/dist/include-openlayers-local.js"></script>
    <style></style>
  </head>

  <body>
    <button onclick="zoomReduce()">缩小</button>
    <button onclick="zoomAdd()">放大</button>
    <button onclick="moveToWuHan()">平移到武汉</button>
    <button onclick="resetMap()">复位</button>
    <button onclick="active()">激活地图事件</button>
    <button onclick="remove()">移除地图事件</button>
    <button onclick="fly()">飞行视角</button>
    <button onclick="removeVetor()">移出矢量点图层</button>
    <button onclick="drawLine()">绘制矢量线图层</button>
    <button onclick="removeLine()">移出矢量线图层</button>
    <button onclick="drawCircle()">绘制矢量圆图层</button>
    <button onclick="removeCircle()">移出矢量圆图层</button>
    <button onclick="drawRectangle()">绘制矢量长方形图层</button>
    <button onclick="removeRectangle()">移出矢量长方形图层</button>
    <button onclick="drawPolygon()">绘制矢量多边形图层</button>
    <button onclick="removePolygon()">移出矢量多边形图层</button>
    <div id="position">坐标X: Y:</div>
    <div id="map"><div id="popup" class="ol-popup"></div></div>
    <script>
      var gaodeMapLayer = new ol.layer.Tile({
        title: '高德地图',
        source: new ol.source.XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
          wrapX: false
        })
      })
      var map = new ol.Map({
        target: 'map',
        layers: [gaodeMapLayer],
        view: new ol.View({
          projection: 'EPSG:4326',
          center: [104.54969, 30.39209],
          zoom: 14
        })
      })
      var view = map.getView()
      var center = view.getCenter()
      var zoom = view.getZoom()
      function zoomReduce() {
        var zoom = view.getZoom()
        view.setZoom(zoom - 1)
      }
      function zoomAdd() {
        var zoom = view.getZoom()
        view.setZoom(zoom + 1)
      }
      function moveToWuHan() {
        var wh = [114, 30.6]
        view.setCenter(wh)
        view.setZoom(14)
      }
      function resetMap() {
        view.setCenter(center)
        view.setZoom(zoom)
      }
      function removeVetor() {
        Point2 = []
        map.removeLayer(vector2)
      }
      var Point2 = []
      var source2
      var vector2
      function handleMap(e) {
        document.getElementById('position').innerHTML = '坐标X:' + e.coordinate[0].toFixed(2) + 'Y:' + e.coordinate[1].toFixed(2)
        var point = new ol.Feature({
          geometry: new ol.geom.Point([e.coordinate[0], e.coordinate[1]])
        })
        var style = new ol.style.Style({
          image: new ol.style.Circle({
            radius: 20,
            fill: new ol.style.Fill({
              color: '#ffcc33'
            })
          })
        })
        Point2.push(point)
        source2 = new ol.source.Vector({
          features: [...Point2]
        })

        if (vector2) {
          map.removeLayer(vector2)
        }
        vector2 = new ol.layer.Vector({
          source: source2
        })
        vector2.setStyle(style)
        map.addLayer(vector2)
      }
      function active() {
        map.on('click', handleMap)
      }
      function remove() {
        map.un('click', handleMap)
      }
      function fly() {
        map.getView().animate({
          center: [104.54969, 30.39209],
          zoom: 14,
          duration: 2000
        })
      }
      //绘制点
      const point1 = new ol.Feature({
        geometry: new ol.geom.Point([114.4, 30.6]),
        name: '武汉市',
        population: 2115
      })
      
      const point2 = new ol.Feature({
        /* 创建点 */
        geometry: new ol.geom.Point([104, 30]),
        name: '成都市',
        population: 2115
      })
      const point3 = new ol.Feature({
        /* 创建点 */
        geometry: new ol.geom.Point([116.5, 39.7]),
        name: '北京市',
        population: 2115
      })
      //设置样式
      const style = new ol.style.Style({
        image: new ol.style.Circle({
          radius: 17,
          fill: new ol.style.Fill({
            color: 'rgba(0,0,0,0.5)'
          }),
          stroke: new ol.style.Stroke({
            color: '#ff2d51',
            width: 4
          })
        })
      })
      //创建数据源
      const source = new ol.source.Vector({
        features: [point1, point2, point3]
      })
      //图层
      const vector = new ol.layer.Vector({
        source: source
      })
      vector.setStyle(style)
      map.addLayer(vector)
      //绘制线
      var LineString = new ol.Feature({
        geometry: new ol.geom.LineString([
          [114.4, 30.6],
          [104, 30]
        ])
      })
      console.log(LineString.getGeometry().getCoordinates())
      LineString.setStyle(
        new ol.style.Style({
          //边线颜色
          stroke: new ol.style.Stroke({
            color: '#ff2d51',
            width: 2
          })
        })
      )
      var linesource = new ol.source.Vector({
        features: [LineString]
      })
      var linevector = new ol.layer.Vector({
        source: linesource
      })
      /* 5、将图层添加到地图容器中 */
      map.addLayer(linevector)
      let lineDraw = false
      let linePoint = []
      var linevectors = []
      function pointDrawlines(e) {
        let linepoint = [e.coordinate[0], e.coordinate[1]]
        linePoint.push(linepoint)
        if (linePoint.length == 2) {
          let LineString = new ol.Feature({
            geometry: new ol.geom.LineString([linePoint[0], linePoint[1]])
          })
          LineString.setStyle(
            new ol.style.Style({
              //边线颜色
              stroke: new ol.style.Stroke({
                color: '#ff2d51',
                width: 4
              })
            })
          )
          let linesource = new ol.source.Vector({
            features: [LineString]
          })
          let linevector = new ol.layer.Vector({
            source: linesource
          })
          linevectors.push(linevector)
          map.addLayer(linevector)
          linePoint = []
        }
      }
      function drawLine() {
        map.on('click', pointDrawlines)
      }
      function removeLine() {
        linePoint = []
        for (let i = 0; i < linevectors.length; i++) {
          map.removeLayer(linevectors[i])
        }
        map.un('click', pointDrawlines)
      }
      //绘制圆
      const Circle1 = new ol.Feature({
        geometry: new ol.geom.Circle([108.95, 34.34], 0.5)
      })
      /* 2、设置样式 */
      Circle1.setStyle(
        new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(120,180,244,0.5)'
          }),
          stroke: new ol.style.Stroke({
            color: '#C9E59E',
            width: 4
          })
        })
      )
      var sourceCircle1 = new ol.source.Vector({
        features: [Circle1]
      })
      var vectorCircle1 = new ol.layer.Vector({
        source: sourceCircle1
      })
      map.addLayer(vectorCircle1)
      let Circles = []
      let vectorCircles
      function pointDrawCircles(e) {
        let circlepoint = [e.coordinate[0], e.coordinate[1]]

        let Circle1 = new ol.Feature({
          geometry: new ol.geom.Circle(circlepoint, 0.5)
        })
        Circles.push(Circle1)
        /* 2、设置样式 */
        Circle1.setStyle(
          new ol.style.Style({
            fill: new ol.style.Fill({
              color: 'rgba(120,180,244,0.5)'
            }),
            stroke: new ol.style.Stroke({
              color: '#C9E59E',
              width: 4
            })
          })
        )
        let sourceCircle1 = new ol.source.Vector({
          features: [...Circles]
        })
        if (vectorCircles) {
          map.removeLayer(vectorCircles)
        }
        vectorCircles = new ol.layer.Vector({
          source: sourceCircle1
        })
        map.addLayer(vectorCircles)
      }
      function drawCircle() {
        map.on('click', pointDrawCircles)
      }
      function removeCircle() {
        map.un('click', pointDrawCircles)
        map.removeLayer(vectorCircles)
        Circles = []
      }
      //绘制正方形
      /* 1、根据圆获取多边形 */
      // [10,0] 绘制的坐标原点  5表示半径
      const SquareCircle = new ol.geom.Circle([113.61, 34.75], 1)
      const Square = new ol.Feature({
        /* 
    第一个参数:Circle(圆对象) 
    第二个参数:正n边形
    第三个参数:旋转的弧度
    */
        geometry: new ol.geom.Polygon.fromCircle(SquareCircle, 4, Math.PI / 3)
      })
      /* 2、设置样式 */
      Square.setStyle(
        new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255,255,255,.7)'
          }),
          stroke: new ol.style.Stroke({
            color: '#333',
            width: 3
          })
        })
      )
      /* 3、设置数据源 */
      var sourceSquare = new ol.source.Vector({
        features: [Square]
      })
      /* 4、创建图层 */
      var vectorSquare = new ol.layer.Vector({
        source: sourceSquare
      })
      /* 5、将图层添加到地图容器中 */
      map.addLayer(vectorSquare)
      const Rectangle = new ol.Feature({
        /*
     第一个参数：左下角
     第二个参数: 右上角
   */
        geometry: new ol.geom.Polygon.fromExtent([106.5, 26.62, 113.23, 23.12])
      })
      /* 2、设置样式 */
      Rectangle.setStyle(
        new ol.style.Style({
          fill: new ol.style.Fill({
            color: 'rgba(255,255,255,.7)'
          }),
          stroke: new ol.style.Stroke({
            color: '#333',
            width: 3
          })
        })
      )
      /* 3、设置数据源 */
      var sourceRectangle = new ol.source.Vector({
        features: [Rectangle]
      })
      /* 4、创建图层 */
      var vectorRectangle = new ol.layer.Vector({
        source: sourceRectangle
      })
      /* 5、将图层添加到地图容器中 */
      map.addLayer(vectorRectangle)
      let rectanglePoints = []
      let vectorRectangles = []
      function pointDrawRectangle(e) {
        let rectanglePoint = [e.coordinate[0], e.coordinate[1]]
        rectanglePoints.push(rectanglePoint)
        if (rectanglePoints.length == 2) {
          let Rectangle = new ol.Feature({
            /*
          第一个参数：左下角
          第二个参数: 右上角
          */
            geometry: new ol.geom.Polygon.fromExtent([...rectanglePoints[0], ...rectanglePoints[1]])
          })
          /* 2、设置样式 */
          Rectangle.setStyle(
            new ol.style.Style({
              fill: new ol.style.Fill({
                color: 'rgba(255,255,255,.7)'
              }),
              stroke: new ol.style.Stroke({
                color: '#333',
                width: 3
              })
            })
          )
          let sourceRectangle = new ol.source.Vector({
            features: [Rectangle]
          })
          /* 4、创建图层 */
          let vectorRectangle = new ol.layer.Vector({
            source: sourceRectangle
          })
          vectorRectangles.push(vectorRectangle)
          map.addLayer(vectorRectangle)
          rectanglePoints = []
        }
      }
      function drawRectangle() {
        map.on('click', pointDrawRectangle)
      }
      function removeRectangle() {
        map.un('click', pointDrawRectangle)
        for (let i = 0; i < vectorRectangles.length; i++) {
          map.removeLayer(vectorRectangles[i])
        }
        rectanglePoints = []
      }
      let Polygonpoints = []
      let vectorPolygons = []
      function pointDrawPolygon(e) {
        let Polygonpoint = [e.coordinate[0], e.coordinate[1]]
        Polygonpoints.push(Polygonpoint)
        if (Polygonpoints.length == numbers) {
          let Polygon = new ol.Feature({
            geometry: new ol.geom.Polygon([[...Polygonpoints]])
          })
          /* 2、设置去样式信息 */
          //设置区样式信息
          Polygon.setStyle(
            new ol.style.Style({
              //填充色
              fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.5)'
              }),
              //边线颜色
              stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 2
              })
            })
          )
          /* 3、设置数据源 */
          let sourcePolygon = new ol.source.Vector({
            features: [Polygon],
            wrapX: false //x轴不重复
          })
          /* 4、创建图层 */
          let vectorPolygon = new ol.layer.Vector({
            source: sourcePolygon
          })
          vectorPolygons.push(vectorPolygon)
          /* 5、将图层添加到地图容器中 */
          map.addLayer(vectorPolygon)
          Polygonpoints = []
        }
      }
      let numbers
      function drawPolygon() {
        Polygonpoints = []
        x = prompt('请输入绘制几边形,只允许输入数字')
        numbers = parseInt(x)
        if (numbers == NaN) {
          alert('请输入数字')
          return
        }
        map.on('click', pointDrawPolygon)
      }
      function removePolygon() {
        for (let i = 0; i < vectorPolygons.length; i++) {
          map.removeLayer(vectorPolygons[i])
        }
        map.un('click', pointDrawPolygon)
        Polygonpoints = []
      }
      console.log(map.getLayers())
      console.log(map.getLayers().array_[5])
      console.log(map.getLayers().array_[5].getSource())
      console.log(map.getLayers().array_[5].getSource().getFeatures()[0])
      console.log(map.getLayers().array_[5].getSource().getFeatures()[0].getGeometry())
      console.log(map.getLayers().array_[5].getSource().getFeatures()[0].getStyle())
      var popup = new ol.Overlay(
        // /** @type {olx.OverlayOptions} */
        {
          //要转换成overlay的HTML元素
          element: document.getElementById('popup'),
          //当前窗口可见
          autoPan: false,
          //Popup放置的位置
          positioning: 'bottom-center',
          //是否应该停止事件传播到地图窗口
          stopEvent: false,
          autoPanAnimation: {
            //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
            duration: 250
          }
        }
      )
      map.addOverlay(popup)
      map.on('click', function (e) {
        var feature = map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
          return feature
        })
        if (feature) {
          document.getElementById('popup').innerHTML = feature.values_.name
          popup.setPosition(feature.values_.geometry.flatCoordinates)
        } else {
          return
        }
      })
    </script>
  </body>
</html>
